package com.example.okhttp.Get;

import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;

import com.example.okhttp.MyCallBack;

import java.io.IOException;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class TestGet {

    //创建日志拦截器
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        //自定义拦截
        @Override
        public void log(String message) {
            //打印日志
            Log.d("guaimiao" , message);
        }
    }).setLevel(HttpLoggingInterceptor.Level.BODY); //添加等级

    private OkHttpClient okHttpClient = new OkHttpClient.Builder()
            //添加日志拦截
            .addInterceptor(interceptor)
            .build();

    private static TestGet testGet;

    //单例模式创建对象
    public static TestGet getInstance() {
        if (testGet == null) {
            testGet = new TestGet();
        }
        return testGet;
    }

    //同步请求
    public String testExecuteGet(String url) throws IOException {
        //将url传进来 获取request对象
        Request request = new Request.Builder()
                .url(url)
                .build();
        //通过okHttpClient的newCall方法 将request传进来 获取Call对象
        Call call = okHttpClient.newCall(request);
        //同步执行
        Response response = call.execute();
        return response.body().string();
    }

    //异步请求
    public void testEnqueueGet(String url, MyCallBack callBack) {

        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onError(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                callBack.onSuccess(string);
            }

        });
    }

}
